package com.kjj.user.service.impl;

import com.kjj.basic.util.AjaxResult;
import com.kjj.basic.util.StrUtils;
import com.kjj.basic.util.VerifyCodeUtils;
import com.kjj.user.domain.Logininfo;
import com.kjj.user.dto.SMSCodeDto;
import com.kjj.user.mapper.LogininfoMapper;
import com.kjj.user.service.IVerifyCodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Value("${sms.code.register.resend-time}")
    private Integer resendTime;
    @Value("${sms.code.register.expire-time}")
    private Integer expireTime;
    @Override
    public String getImageCode(String key) throws IOException {
        //生成4为验证码
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        //验证吗放入redis，并且3分钟过期时间
        redisTemplate.opsForValue().set("imgVerifyCode_"+key,verifyCode,3, TimeUnit.MINUTES);
        //把验证码合成图片并加密为base64数据进行返回
        String base64Data = VerifyCodeUtils.VerifyCode(140,50,verifyCode);
        return base64Data;
    }

    @Override
    public AjaxResult sendSmsRegisterCode(SMSCodeDto smsCodeDto) {
        String mobile = smsCodeDto.getMobile();
        String imageCode = smsCodeDto.getImageCode();
        String imageCodeKey = smsCodeDto.getImageCodeKey();
        //判空
        if (StringUtils.isEmpty(mobile)||StringUtils.isEmpty(imageCode)||StringUtils.isEmpty(imageCodeKey))
            return AjaxResult.me().setSuccess(false).setMessage("非法使用，参数异常");
        String imgCode_Redis = (String) redisTemplate.opsForValue().get("imgVerifyCode_" + imageCodeKey);
        if (!imageCode.trim().equalsIgnoreCase(imgCode_Redis)){
            return AjaxResult.me().setSuccess(false).setMessage("请输入正确的图片验证码");
        }
        //判断手机号是否已经被注册
        Logininfo logininfo = logininfoMapper.loadUserByMobile(mobile);
        if (logininfo != null) {
            return AjaxResult.me().setSuccess(false).setMessage("该手机号已经被注册！请登录使用");
        }
//2 判断原来的验证码是否存在
        String key ="register_sms_code_" + mobile;

        String smsCodeOfRedis = (String) redisTemplate.opsForValue()
                .get(key);
        String code = "";
        if (StringUtils.isEmpty(smsCodeOfRedis)) {
            //2.1 如果不存在就产生新的
            code = StrUtils.getRandomString(6);
        }else{
            //2.2 如果存在，判断是否已过重发时间，如果没有过报错，过了直接原来的
            code = smsCodeOfRedis.split(":")[0];              //code:time
            String time = smsCodeOfRedis.split(":")[1];              //code:time
            if (System.currentTimeMillis()-new Date(Long.valueOf(time)).getTime() <= 60*1000*resendTime)  //60*1000
            {
                return AjaxResult.me().setSuccess(false).setMessage("非法请求，请勿乱搞！");
            }
        }
        //3 记录验证码到redis
        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),expireTime, TimeUnit.MINUTES);
        //4 调用短信接口进行发送
        String content = String.format("你的验证码为%s,请在%s分钟之内使用！", code, expireTime);
        //SmsUtil.sendSms(mobile,content);
        System.out.println("已经成功发送了一条短信,内容为"+content);
        return AjaxResult.me();
    }

    @Override
    public AjaxResult sendSmsLoginCode(SMSCodeDto smsCodeDto) {

        String mobile = smsCodeDto.getMobile();
        //判空
        if (StringUtils.isEmpty(mobile))
            return AjaxResult.me().setSuccess(false).setMessage("非法使用，参数异常");
        //判断手机号是否可发送验证码
/*        Logininfo logininfo = logininfoMapper.loadUserByMobile(mobile);
        if (logininfo == null) {
            return AjaxResult.me().setSuccess(false).setMessage("该手机号未被注册！请注册使用");
        }*/
//2 判断原来的验证码是否存在
        String key ="login_sms_code_" + mobile;

        String smsCodeOfRedis = (String) redisTemplate.opsForValue()
                .get(key);
        String code = "";
        if (StringUtils.isEmpty(smsCodeOfRedis)) {
            //2.1 如果不存在就产生新的
            code = StrUtils.getRandomString(6);
        }else{
            //2.2 如果存在，判断是否已过重发时间，如果没有过报错，过了直接原来的
            code = smsCodeOfRedis.split(":")[0];              //code:time
            String time = smsCodeOfRedis.split(":")[1];              //code:time
            if (System.currentTimeMillis()-new Date(Long.valueOf(time)).getTime() <= 60*1000*resendTime)  //60*1000
            {
                return AjaxResult.me().setSuccess(false).setMessage("非法请求，请勿乱搞！");
            }
        }
        //3 记录验证码到redis
        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),expireTime, TimeUnit.MINUTES);
        //4 调用短信接口进行发送
        String content = String.format("你的验证码为%s,请在%s分钟之内使用！", code, expireTime);
        //SmsUtil.sendSms(mobile,content);
        System.out.println("已经成功发送了一条短信,内容为"+content);
        return AjaxResult.me();
    }
}
